

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletResponse;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;

@Component
@Aspect
public class LoginPointcutAdvisor {

	

	
	/**
	 * 	public final Object invokeHandlerMethod(Method handlerMethod, Object handler,
			NativeWebRequest webRequest, ExtendedModelMap implicitModel) throws Exception {
	 * @throws Throwable 
	 * 
	 */
	
	@Around("execution(* org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter$ServletHandlerMethodInvoker.invokeHandlerMethod(..))") 
	public Object loginInterceptor(ProceedingJoinPoint  pip) throws Throwable{
		Method handlerMethod = (Method)pip.getArgs()[0];
		NativeWebRequest webReques = (NativeWebRequest)pip.getArgs()[1];
		LoginRequired loginRequired = handlerMethod.getAnnotation(LoginRequired.class);
		if(loginRequired != null){
			Object userId = webReques.getAttribute(PassportInterceptor.USER_ID_ATTR_NAME, RequestAttributes.SCOPE_REQUEST);
			if(userId == null){
				HttpServletResponse response = (HttpServletResponse)webReques.getNativeResponse();
				response.sendError(HttpStatus.FORBIDDEN.value());
				return null;
			}
		}
		
		Object retVal =  pip.proceed();
		return retVal;
	}
	
//	@Around("execution(* org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(..))") 
//	public Object loginInterceptor2(ProceedingJoinPoint  pip) throws Throwable{
//		Object retVal =  pip.proceed();
//		return retVal;
//	}
	
	@Around("execution(* com.sohu.cloudatlas.controller.*.*(..))") 
	public Object loginInterceptor3(ProceedingJoinPoint  pip) throws Throwable{
		Object retVal =  pip.proceed();
		return retVal;
	}
	
}
